package com.cocos.game.zdkj.net;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.cocos.game.ZDKJUtils;
import com.cocos.game.zdkj.model.BaseResponse;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public abstract class ApiCallBack implements Callback {
    @Override
    public void onFailure(@NonNull Call call, @NonNull IOException e) {
        try {
            onError(NetApiCode.OTHER_ERROR, e.getMessage());
        } catch (Throwable t) {
            onError(NetApiCode.OTHER_ERROR, t.getMessage());
        }
    }

    @Override
    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
        if (response.isSuccessful()) {
            if(response.body() == null){
                onError(NetApiCode.BUSINESS_FAIL,"body is null");
            }else {
                String res = response.body().string();
                try {
                    BaseResponse baseResponse = ZDKJUtils.gson.fromJson(res, BaseResponse.class);
                    if(baseResponse.isSuccess()){
                        onSuccess(baseResponse);
                    }else {
                        onError(NetApiCode.BUSINESS_FAIL, baseResponse.getCode() + "-" +baseResponse.getMessage());
                    }
                } catch (Exception e) {
                    onError(NetApiCode.OTHER_ERROR, e.getMessage());
                }
            }
        } else {
            onError(NetApiCode.NET_FAIL, "http响应失败" + response.code());
        }
    }


    protected abstract void onComplete();

    protected abstract void onSuccess(@Nullable BaseResponse data);

    protected abstract void onError(int code, String message);

}
